package me.principality.webapp.response

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice

@RestControllerAdvice
class ResponseAdvice : ResponseBodyAdvice<Any?> {
    @Autowired
    private val objectMapper: ObjectMapper? = null
    override fun supports(
        methodParameter: MethodParameter,
        aClass: Class<out HttpMessageConverter<*>>
    ): Boolean {
        if (methodParameter.hasMethodAnnotation(VueDataFormat::class.java)) {
            return true
        }
        return false
    }

    override fun beforeBodyWrite(
        o: Any?,
        methodParameter: MethodParameter,
        mediaType: MediaType,
        aClass: Class<out HttpMessageConverter<*>>,
        serverHttpRequest: ServerHttpRequest,
        serverHttpResponse: ServerHttpResponse
    ): Any? {
        return if (o is String) {
            objectMapper?.writeValueAsString(ResultData.success(o))
        } else if (o is ResultData<*>) {
            o
        } else {
            ResultData.success(o)
        }
    }
}